<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

// 处理导出请求 - 必须在包含header之前
if (isset($_GET['export']) && $_GET['export'] == 'settlements') {
    exportSettlementsToExcel();
    exit;
}

// 获取筛选条件
$status = $_GET['status'] ?? '';
$user_id = $_GET['user_id'] ?? '';
$phone = $_GET['phone'] ?? ''; // 新增手机号筛选
$tracking_no = $_GET['tracking_no'] ?? ''; // 新增物流单号筛选
$date_range = $_GET['date_range'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;

// 构建查询条件
$where = ['1=1'];
$params = [];

if ($status && in_array($status, ['pending', 'completed'])) {
    $where[] = 's.status = ?';
    $params[] = $status;
}

if ($user_id) {
    $where[] = 's.user_id = ?';
    $params[] = intval($user_id);
}

// 新增手机号筛选条件
if ($phone) {
    $where[] = 'u.phone LIKE ?';
    $params[] = '%' . $phone . '%';
}

// 新增物流单号筛选条件
if ($tracking_no) {
    $where[] = 'EXISTS (SELECT 1 FROM orders o WHERE JSON_CONTAINS(s.order_ids, CAST(o.id AS CHAR)) AND o.tracking_no LIKE ?)';
    $params[] = '%' . $tracking_no . '%';
}

// 处理日期范围筛选
if ($date_range) {
    $date_parts = explode(' - ', $date_range);
    if (count($date_parts) === 2) {
        $start_date = trim($date_parts[0]);
        $end_date = trim($date_parts[1]);
        
        // 验证日期格式
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
            $where[] = 'DATE(s.created_at) BETWEEN ? AND ?';
            $params[] = $start_date;
            $params[] = $end_date;
        }
    }
}

$whereClause = implode(' AND ', $where);

// 获取结算记录总数
$db = getDB();
$stmt = $db->prepare("SELECT COUNT(*) FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();

// 计算分页
$totalPages = ceil($total / $perPage);
$page = min($page, $totalPages ?: 1);
$offset = ($page - 1) * $perPage;

// 获取结算记录列表
$stmt = $db->prepare("SELECT s.*, u.username, u.phone, u.group_name FROM settlements s 
                     LEFT JOIN users u ON s.user_id = u.id 
                     WHERE $whereClause 
                     ORDER BY s.created_at DESC 
                     LIMIT $offset, $perPage");
$stmt->execute($params);
$settlements = $stmt->fetchAll();

// 处理结算状态变更
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $settlementId = intval($_POST['settlement_id'] ?? 0);
    
    if ($settlementId <= 0) {
        $error = '结算记录ID无效';
    } else {
        if ($action == 'complete') {
            // 获取结算信息和截图
            $settlementInfo = $_POST['settlement_info'] ?? '';
            $settlementScreenshots = [];
            
            // 处理截图上传
            if (isset($_FILES['settlement_screenshots']) && is_array($_FILES['settlement_screenshots']['name'])) {
                foreach ($_FILES['settlement_screenshots']['name'] as $key => $name) {
                    if ($_FILES['settlement_screenshots']['error'][$key] === UPLOAD_ERR_OK) {
                        $file = [
                            'name' => $name,
                            'type' => $_FILES['settlement_screenshots']['type'][$key],
                            'tmp_name' => $_FILES['settlement_screenshots']['tmp_name'][$key],
                            'error' => $_FILES['settlement_screenshots']['error'][$key],
                            'size' => $_FILES['settlement_screenshots']['size'][$key]
                        ];
                        
                        $uploadResult = uploadFile($file, 'settlement_screenshot');
                        if ($uploadResult['success']) {
                            $settlementScreenshots[] = $uploadResult['filename'];
                        }
                    }
                }
            }
            
            // 完成结算
            $stmt = $db->prepare("UPDATE settlements SET status = 'completed', settled_at = NOW(), settlement_info = ?, settlement_screenshots = ? WHERE id = ?");
            if ($stmt->execute([$settlementInfo, json_encode($settlementScreenshots), $settlementId])) {
                $success = '结算完成';
                
                // 获取结算详细信息
                $stmt = $db->prepare("SELECT s.*, u.username, u.pushplus_enabled, u.pushplus_token, u.wechat_account, u.alipay_account FROM settlements s 
                                   LEFT JOIN users u ON s.user_id = u.id 
                                   WHERE s.id = ?");
                $stmt->execute([$settlementId]);
                $settlement = $stmt->fetch();
                
                if ($settlement) {
                    // 获取关联的订单详情
                    $orderIds = json_decode($settlement['order_ids'], true);
                    $orderDetails = [];
                    if (!empty($orderIds)) {
                        $placeholders = str_repeat('?,', count($orderIds) - 1) . '?';
                        $stmt = $db->prepare("SELECT id, product_name, order_amount, settlement_amount FROM orders WHERE id IN ($placeholders)");
                        $stmt->execute($orderIds);
                        $orderDetails = $stmt->fetchAll();
                    }
                    
                    // 发送结算完成通知
                    if ($settlement['pushplus_enabled'] && !empty($settlement['pushplus_token'])) {
                        try {
                            sendSettlementNotification($settlement['user_id'], $settlementId, $orderDetails);
                        } catch (Exception $e) {
                            // 推送失败不影响正常流程
                            error_log("PushPlus推送失败: " . $e->getMessage());
                        }
                    }
                }
            } else {
                $error = '结算更新失败';
            }
        } elseif ($action == 'delete') {
            // 删除结算记录
            $stmt = $db->prepare("DELETE FROM settlements WHERE id = ?");
            if ($stmt->execute([$settlementId])) {
                $success = '结算记录删除成功';
            } else {
                $error = '结算记录删除失败';
            }
        }
    }
    
    // 重新获取结算记录列表
    $stmt = $db->prepare("SELECT s.*, u.username, u.phone, u.group_name FROM settlements s 
                         LEFT JOIN users u ON s.user_id = u.id 
                         WHERE $whereClause 
                         ORDER BY s.created_at DESC 
                         LIMIT $offset, $perPage");
    $stmt->execute($params);
    $settlements = $stmt->fetchAll();
}

// 获取用户列表（用于筛选）
$stmt = $db->query("SELECT id, username, phone FROM users WHERE status = 1 ORDER BY username");
$usersList = $stmt->fetchAll();

/**
 * 更新结算金额
 */
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_settlement_amount') {
    $settlementId = intval($_POST['settlement_id'] ?? 0);
    $newAmount = floatval($_POST['new_amount'] ?? 0);
    $adjustmentReason = $_POST['adjustment_reason'] ?? '';
    
    if ($settlementId <= 0 || $newAmount <= 0) {
        echo json_encode(['success' => false, 'message' => '参数无效']);
        exit;
    }
    
    if (empty($adjustmentReason)) {
        echo json_encode(['success' => false, 'message' => '请填写金额调整原因']);
        exit;
    }
    
    $db = getDB();
    
    // 获取原金额
    $stmt = $db->prepare("SELECT total_amount FROM settlements WHERE id = ?");
    $stmt->execute([$settlementId]);
    $settlement = $stmt->fetch();
    
    if (!$settlement) {
        echo json_encode(['success' => false, 'message' => '结算记录不存在']);
        exit;
    }
    
    $oldAmount = $settlement['total_amount'];
    
    // 更新结算金额
    $stmt = $db->prepare("UPDATE settlements SET total_amount = ?, settlement_info = CONCAT(COALESCE(settlement_info, ''), '\n\n【金额调整】', ?, ' 原金额：', ?, ' → 新金额：', ?) WHERE id = ?");
    
    $adjustmentNote = "\n调整时间：" . date('Y-m-d H:i:s') . "\n调整原因：" . $adjustmentReason . "\n原金额：¥" . number_format($oldAmount, 2) . " → 新金额：¥" . number_format($newAmount, 2);
    
    if ($stmt->execute([$newAmount, $adjustmentNote, $oldAmount, $newAmount, $settlementId])) {
        echo json_encode(['success' => true, 'message' => '结算金额更新成功']);
        
        // 记录安全日志
        logSecurityEvent('settlement_amount_adjusted', $_SESSION['user_id'], "结算ID: $settlementId, 原金额: $oldAmount, 新金额: $newAmount, 原因: $adjustmentReason");
    } else {
        echo json_encode(['success' => false, 'message' => '结算金额更新失败']);
    }
    exit;
}

/**
 * 导出结算记录到Excel
 */
function exportSettlementsToExcel() {
    $db = getDB();
    
    // 获取导出参数
    $export_type = $_GET['export_type'] ?? 'current_page';
    $selected_ids = $_GET['selected_ids'] ?? '';
    
    // 构建查询条件（与页面筛选条件一致）
    $where = ['1=1'];
    $params = [];
    
    $status = $_GET['status'] ?? '';
    $user_id = $_GET['user_id'] ?? '';
    $phone = $_GET['phone'] ?? '';
    $tracking_no = $_GET['tracking_no'] ?? ''; // 新增物流单号筛选
    $date_range = $_GET['date_range'] ?? '';
    
    if ($status && in_array($status, ['pending', 'completed'])) {
        $where[] = 's.status = ?';
        $params[] = $status;
    }
    
    if ($user_id) {
        $where[] = 's.user_id = ?';
        $params[] = intval($user_id);
    }
    
    if ($phone) {
        $where[] = 'u.phone LIKE ?';
        $params[] = '%' . $phone . '%';
    }
    
    // 新增物流单号筛选条件
    if ($tracking_no) {
        $where[] = 'EXISTS (SELECT 1 FROM orders o WHERE JSON_CONTAINS(s.order_ids, CAST(o.id AS CHAR)) AND o.tracking_no LIKE ?)';
        $params[] = '%' . $tracking_no . '%';
    }
    
    if ($date_range) {
        $date_parts = explode(' - ', $date_range);
        if (count($date_parts) === 2) {
            $start_date = trim($date_parts[0]);
            $end_date = trim($date_parts[1]);
            
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
                $where[] = 'DATE(s.created_at) BETWEEN ? AND ?';
                $params[] = $start_date;
                $params[] = $end_date;
            }
        }
    }
    
    $whereClause = implode(' AND ', $where);
    
    // 根据导出类型获取结算记录ID
    $settlement_ids = [];
    
    if ($export_type == 'selected' && $selected_ids) {
        // 导出选中的结算记录
        $settlement_ids = explode(',', $selected_ids);
        $settlement_ids = array_map('intval', $settlement_ids);
    } elseif ($export_type == 'all') {
        // 导出所有符合条件的结算记录
        $stmt = $db->prepare("SELECT s.id FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $whereClause ORDER BY s.created_at DESC");
        $stmt->execute($params);
        $all_settlements = $stmt->fetchAll();
        $settlement_ids = array_column($all_settlements, 'id');
    } else {
        // 导出当前页 - 这里需要重新查询当前页数据
        $page = max(1, intval($_GET['page'] ?? 1));
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        $stmt = $db->prepare("SELECT s.id FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $whereClause ORDER BY s.created_at DESC LIMIT $offset, $perPage");
        $stmt->execute($params);
        $current_settlements = $stmt->fetchAll();
        $settlement_ids = array_column($current_settlements, 'id');
    }
    
    if (empty($settlement_ids)) {
        // 如果没有数据，返回错误
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => '没有可导出的结算记录']);
        exit;
    }
    
    // 获取结算记录详情
    $placeholders = str_repeat('?,', count($settlement_ids) - 1) . '?';
    $stmt = $db->prepare("
        SELECT 
            s.*,
            u.username,
            u.phone,
            u.group_name,
            u.wechat_account,
            u.alipay_account,
            u.bank_card_number,
            u.account_holder,
            u.bank_name
        FROM settlements s 
        LEFT JOIN users u ON s.user_id = u.id 
        WHERE s.id IN ($placeholders)
        ORDER BY s.created_at DESC
    ");
    $stmt->execute($settlement_ids);
    $settlements = $stmt->fetchAll();
    
    // 设置响应头
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment;filename="结算记录_' . date('YmdHis') . '.xls"');
    header('Cache-Control: max-age=0');
    header('Expires: 0');
    header('Pragma: public');
    
    // 开始输出
    echo "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">";
    echo "<head>";
    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
    echo "<!--[if gte mso 9]>";
    echo "<xml>";
    echo "<x:ExcelWorkbook>";
    echo "<x:ExcelWorksheets>";
    echo "<x:ExcelWorksheet>";
    echo "<x:Name>结算记录</x:Name>";
    echo "<x:WorksheetOptions>";
    echo "<x:DisplayGridlines/>";
    echo "</x:WorksheetOptions>";
    echo "</x:ExcelWorksheet>";
    echo "</x:ExcelWorksheets>";
    echo "</x:ExcelWorkbook>";
    echo "</xml>";
    echo "<![endif]-->";
    echo "<style>";
    echo "td { mso-number-format:\"\\@\"; }";
    echo ".text { mso-number-format:\"\\@\"; }";
    echo "</style>";
    echo "</head>";
    echo "<body>";
    
    // 输出结算记录基本信息表格
    echo "<table border='1'>";
    echo "<tr><th colspan='16' style='background-color: #4e73df; color: white; font-size: 16px; padding: 10px;'>结算记录基本信息</th></tr>";
    echo "<tr style='background-color: #f8f9fa;'>";
    echo "<th>结算ID</th><th>用户名</th><th>手机号</th><th>群组</th><th>结算类型</th><th>总金额</th>";
    echo "<th>订单数量</th><th>状态</th><th>创建时间</th><th>结算时间</th><th>微信账号</th>";
    echo "<th>支付宝账号</th><th>银行卡号</th><th>开户人</th><th>银行名称</th><th>结算备注</th>";
    echo "</tr>";
    
    foreach ($settlements as $settlement) {
        $status_text = $settlement['status'] == 'completed' ? '已结算' : '待结算';
        $type_text = $settlement['settlement_type'] == 'commission' ? '结本金' : '结本金+佣金';
        $group_name_label = getConfigOptionLabel('group_name', $settlement['group_name']);
        $order_ids = json_decode($settlement['order_ids'], true) ?: [];
        
        echo "<tr>";
        echo "<td>{$settlement['id']}</td>";
        echo "<td>{$settlement['username']}</td>";
        echo "<td>{$settlement['phone']}</td>";
        echo "<td>{$group_name_label}</td>";
        echo "<td>{$type_text}</td>";
        echo "<td>¥" . number_format($settlement['total_amount'], 2) . "</td>";
        echo "<td>" . count($order_ids) . "</td>";
        echo "<td>{$status_text}</td>";
        echo "<td>{$settlement['created_at']}</td>";
        echo "<td>" . ($settlement['settled_at'] ?: '-') . "</td>";
        echo "<td>" . ($settlement['wechat_account'] ?: '-') . "</td>";
        echo "<td>" . ($settlement['alipay_account'] ?: '-') . "</td>";
        echo "<td>" . ($settlement['bank_card_number'] ?: '-') . "</td>";
        echo "<td>" . ($settlement['account_holder'] ?: '-') . "</td>";
        echo "<td>" . ($settlement['bank_name'] ?: '-') . "</td>";
        echo "<td>" . ($settlement['settlement_info'] ?: '-') . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<br><br>";
    
    // 输出关联订单详情
    echo "<table border='1'>";
    echo "<tr><th colspan='9' style='background-color: #1cc88a; color: white; font-size: 16px; padding: 10px;'>关联订单详情</th></tr>";
    echo "<tr style='background-color: #f8f9fa;'>";
    echo "<th>结算ID</th><th>订单ID</th><th>商品名称</th><th>收货地</th><th>下单平台</th>";
    echo "<th>物流单号</th><th>下单金额</th><th>结算金额</th><th>下单时间</th>";
    echo "</tr>";
    
    foreach ($settlements as $settlement) {
        $order_ids = json_decode($settlement['order_ids'], true);
        if (empty($order_ids)) continue;
        
        $placeholders = str_repeat('?,', count($order_ids) - 1) . '?';
        $stmt = $db->prepare("
            SELECT 
                id, product_name, delivery_location, order_platform,
                tracking_no, order_amount, created_at
            FROM orders 
            WHERE id IN ($placeholders)
            ORDER BY id
        ");
        $stmt->execute($order_ids);
        $orders = $stmt->fetchAll();
        
        foreach ($orders as $order) {
            $delivery_location_label = getConfigOptionLabel('delivery_location', $order['delivery_location']);
            $order_platform_label = getConfigOptionLabel('order_platform', $order['order_platform']);
            
            echo "<tr>";
            echo "<td>{$settlement['id']}</td>";
            echo "<td>{$order['id']}</td>";
            echo "<td>{$order['product_name']}</td>";
            echo "<td>{$delivery_location_label}</td>";
            echo "<td>{$order_platform_label}</td>";
            echo "<td>" . ($order['tracking_no'] ?: '-') . "</td>";
            echo "<td>¥" . number_format($order['order_amount'], 2) . "</td>";
            echo "<td>¥" . number_format($order['order_amount'], 2) . "</td>"; // 可根据实际情况调整
            echo "<td>{$order['created_at']}</td>";
            echo "</tr>";
        }
    }
    echo "</table>";
    
    echo "<br><br>";
    
    // 输出结算单子详情 - 修改这里，移除对admins表的关联
    echo "<table border='1'>";
    echo "<tr><th colspan='8' style='background-color: #36b9cc; color: white; font-size: 16px; padding: 10px;'>结算单子详情</th></tr>";
    echo "<tr style='background-color: #f8f9fa;'>";
    echo "<th>结算ID</th><th>结算子ID</th><th>订单ID</th><th>商品名称</th><th>结算类型</th>";
    echo "<th>结算金额</th><th>结算时间</th><th>结算信息</th>";
    echo "</tr>";
    
    // 检查settlement_details表是否存在
    try {
        $placeholders = str_repeat('?,', count($settlement_ids) - 1) . '?';
        $stmt = $db->prepare("
            SELECT 
                sd.*,
                o.product_name
            FROM settlement_details sd
            LEFT JOIN orders o ON sd.order_id = o.id
            WHERE sd.settlement_id IN ($placeholders)
            ORDER BY sd.created_at DESC
        ");
        $stmt->execute($settlement_ids);
        $settlement_details = $stmt->fetchAll();
        
        foreach ($settlement_details as $detail) {
            $type_text = $detail['settlement_type'] == 'commission' ? '结本金' : '结本金+佣金';
            
            echo "<tr>";
            echo "<td>{$detail['settlement_id']}</td>";
            echo "<td>{$detail['id']}</td>";
            echo "<td>{$detail['order_id']}</td>";
            echo "<td>{$detail['product_name']}</td>";
            echo "<td>{$type_text}</td>";
            echo "<td>¥" . number_format($detail['settlement_amount'], 2) . "</td>";
            echo "<td>{$detail['created_at']}</td>";
            echo "<td>" . ($detail['settlement_info'] ?: '-') . "</td>";
            echo "</tr>";
        }
    } catch (Exception $e) {
        // 如果settlement_details表也不存在，输出提示
        echo "<tr><td colspan='8' style='text-align: center; color: #666;'>结算单子详情表不存在</td></tr>";
    }
    echo "</table>";
    
    echo "</body></html>";
    exit;
}

include __DIR__ . '/header.php';
?>
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">结算管理</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#exportModal">
                            <i class="bi bi-download"></i> 导出结算记录
                        </button>
                    </div>
                </div>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            

            <!-- 筛选器 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-2">
                            <label for="status" class="form-label">结算状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">全部状态</option>
                                <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>待结算</option>
                                <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>已结算</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="user_id" class="form-label">用户筛选</label>
                            <select class="form-select" id="user_id" name="user_id">
                                <option value="">全部用户</option>
                                <?php foreach ($usersList as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" 
                                            <?php echo $user_id == $user['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['username']); ?> (<?php echo $user['phone']; ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="phone" class="form-label">手机号</label>
                            <input type="text" class="form-control" id="phone" name="phone" 
                                   value="<?php echo htmlspecialchars($phone); ?>" 
                                   placeholder="输入手机号">
                        </div>
                        <div class="col-md-2">
                            <label for="tracking_no" class="form-label">物流单号</label>
                            <input type="text" class="form-control" id="tracking_no" name="tracking_no" 
                                   value="<?php echo htmlspecialchars($tracking_no); ?>" 
                                   placeholder="输入物流单号">
                        </div>
                        <div class="col-md-2">
                            <label for="date_range" class="form-label">创建日期范围</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="date_range" name="date_range" 
                                       value="<?php echo htmlspecialchars($date_range); ?>" 
                                       placeholder="开始日期 - 结束日期" readonly>
                                <button type="button" class="btn btn-outline-secondary" onclick="clearDateRange()">
                                    <i class="bi bi-x-circle"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <a href="settlements.php" class="btn btn-secondary">
                                <i class="bi bi-arrow-counterclockwise"></i> 重置
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">
                                <i class="bi bi-clock-history"></i> 待结算
                            </h5>
                            <?php
                            // 构建待结算的查询条件
                            $wherePending = $where;
                            $wherePending[] = "s.status = 'pending'";
                            $wherePendingClause = implode(' AND ', $wherePending);
                            
                            $stmt = $db->prepare("SELECT COUNT(*) FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $wherePendingClause");
                            $stmt->execute($params);
                            $pendingCount = $stmt->fetchColumn();
                            ?>
                            <h3 class="mb-0"><?php echo $pendingCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">
                                <i class="bi bi-check-circle"></i> 已结算
                            </h5>
                            <?php
                            // 构建已结算的查询条件
                            $whereCompleted = $where;
                            $whereCompleted[] = "s.status = 'completed'";
                            $whereCompletedClause = implode(' AND ', $whereCompleted);
                            
                            $stmt = $db->prepare("SELECT COUNT(*) FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $whereCompletedClause");
                            $stmt->execute($params);
                            $completedCount = $stmt->fetchColumn();
                            ?>
                            <h3 class="mb-0"><?php echo $completedCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">
                                <i class="bi bi-currency-yen"></i> 待结算总额
                            </h5>
                            <?php
                            $stmt = $db->prepare("SELECT SUM(total_amount) FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $wherePendingClause");
                            $stmt->execute($params);
                            $pendingAmount = $stmt->fetchColumn() ?: 0;
                            ?>
                            <h3 class="mb-0"><?php echo formatAmount($pendingAmount); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-primary text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">
                                <i class="bi bi-currency-yen"></i> 已结算总额
                            </h5>
                            <?php
                            $stmt = $db->prepare("SELECT SUM(total_amount) FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE $whereCompletedClause");
                            $stmt->execute($params);
                            $completedAmount = $stmt->fetchColumn() ?: 0;
                            ?>
                            <h3 class="mb-0"><?php echo formatAmount($completedAmount); ?></h3>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 导出模态框 -->
            <div class="modal fade" id="exportModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">导出结算记录</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">导出范围</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="export_scope" id="export_current" value="current_page" checked>
                                    <label class="form-check-label" for="export_current">
                                        当前页结算记录 (<?php echo count($settlements); ?>条)
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="export_scope" id="export_selected" value="selected">
                                    <label class="form-check-label" for="export_selected">
                                        选中的结算记录 (<span id="selected_count">0</span>条)
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="export_scope" id="export_all" value="all">
                                    <label class="form-check-label" for="export_all">
                                        全部符合条件的结算记录 (<?php echo $total; ?>条)
                                    </label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">导出格式</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="export_format" id="format_excel" value="excel" checked>
                                    <label class="form-check-label" for="format_excel">
                                        Excel格式 (.xls)
                                    </label>
                                </div>
                            </div>
                            <div class="alert alert-info">
                                <i class="bi bi-info-circle"></i>
                                <strong>导出内容包含：</strong><br>
                                • 结算基本信息<br>
                                • 关联订单详情<br>
                                • 结算单子详情
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirmExport">
                                <i class="bi bi-download"></i> 开始导出
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 结算记录列表 -->
            <div class="card">
                <div class="card-body">
                    <?php if (empty($settlements)): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-inbox display-1 text-muted"></i>
                            <h4 class="mt-3 text-muted">暂无结算记录</h4>
                            <p class="text-muted">还没有生成任何结算记录</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th width="40">
                                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                                        </th>
                                        <th>ID</th>
                                        <th>用户</th>
                                        <th>群组</th>
                                        <th>结算类型</th>
                                        <th>总金额</th>
                                        <th>订单数量</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>结算时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($settlements as $settlement): ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" class="settlement-checkbox" value="<?php echo $settlement['id']; ?>">
                                            </td>
                                            <td><?php echo $settlement['id']; ?></td>
                                            <td>
                                                <?php echo htmlspecialchars($settlement['username']); ?>
                                                <br>
                                                <small class="text-muted"><?php echo htmlspecialchars($settlement['phone']); ?></small>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(getConfigOptionLabel('group_name', $settlement['group_name'])); ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $settlement['settlement_type'] == 'commission' ? 'info' : 'primary'; ?>">
                                                    <?php echo $settlement['settlement_type'] == 'commission' ? '本金' : '本金+佣金'; ?>
                                                </span>
                                            </td>
                                            <td class="text-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?> fw-bold">
                                                <?php echo formatAmount($settlement['total_amount']); ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $orderIds = json_decode($settlement['order_ids'], true);
                                                echo count($orderIds ?: []);
                                                ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?>">
                                                    <?php echo $settlement['status'] == 'completed' ? '已结算' : '待结算'; ?>
                                                </span>
                                            </td>
                                            <td><?php echo formatTime($settlement['created_at']); ?></td>
                                            <td>
                                                <?php if ($settlement['settled_at']): ?>
                                                    <?php echo formatTime($settlement['settled_at']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <!-- 在 settlements.php 的操作列部分修改 -->
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                            onclick="showSettlementDetails(<?php echo $settlement['id']; ?>)"
                                                            data-bs-toggle="tooltip" title="查看详情">
                                                        <i class="bi bi-eye"></i>
                                                    </button>
                                                    
                                                    <?php if ($settlement['status'] == 'pending'): ?>
                                                        <button type="button" class="btn btn-sm btn-outline-success" 
                                                                onclick="showCompleteSettlement(<?php echo $settlement['id']; ?>)"
                                                                data-bs-toggle="tooltip" title="完成结算">
                                                            <i class="bi bi-check-circle"></i>
                                                        </button>
                                                    <?php else: ?>
                                                        <!-- 已结算的记录显示修改按钮 -->
                                                        <button type="button" class="btn btn-sm btn-outline-warning" 
                                                                onclick="showEditSettlementModal(<?php echo $settlement['id']; ?>)"
                                                                data-bs-toggle="tooltip" title="修改结算信息">
                                                            <i class="bi bi-pencil-square"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-outline-info" 
                                                                onclick="showEditSettlementAmount(<?php echo $settlement['id']; ?>)"
                                                                data-bs-toggle="tooltip" title="修改结算金额">
                                                            <i class="bi bi-currency-exchange"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    
                                                    <form method="POST" style="display: inline;" 
                                                          onsubmit="return confirm('确定要删除这个结算记录吗？此操作不可恢复！');">
                                                        <input type="hidden" name="action" value="delete">
                                                        <input type="hidden" name="settlement_id" value="<?php echo $settlement['id']; ?>">
                                                        <button type="submit" class="btn btn-sm btn-outline-danger" 
                                                                data-bs-toggle="tooltip" title="删除">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <?php if ($totalPages > 1): ?>
                            <nav aria-label="结算分页" class="mt-4">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status; ?>&user_id=<?php echo $user_id; ?>&phone=<?php echo urlencode($phone); ?>&date_range=<?php echo urlencode($date_range); ?>">
                                            <i class="bi bi-chevron-left"></i> 上一页
                                        </a>
                                    </li>
                                    
                                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                        <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status; ?>&user_id=<?php echo $user_id; ?>&phone=<?php echo urlencode($phone); ?>&date_range=<?php echo urlencode($date_range); ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                        <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                    <?php endfor; ?>
                                    
                                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status; ?>&user_id=<?php echo $user_id; ?>&phone=<?php echo urlencode($phone); ?>&date_range=<?php echo urlencode($date_range); ?>">
                                            下一页 <i class="bi bi-chevron-right"></i>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>


<!-- 结算详情模态框 -->
<div class="modal fade" id="completeSettlementModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">结算详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="completeSettlementContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmCompleteSettlement">
                    <i class="bi bi-check-circle"></i> 确认结算
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 结算详情模态框 -->
<div class="modal fade" id="settlementDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">结算详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="settlementDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
<!-- 修改结算信息模态框 -->
<div class="modal fade" id="editSettlementModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改结算信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="editSettlementContent">
                <!-- 内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 修改结算金额模态框 -->
<div class="modal fade" id="editSettlementAmountModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改结算金额</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="newAmount" class="form-label">新的结算金额</label>
                    <input type="number" class="form-control" id="newAmount" step="0.01" min="0.01" required>
                    <div class="form-text">请输入正确的金额，支持小数点后两位</div>
                </div>
                <div class="mb-3">
                    <label for="adjustmentReason" class="form-label">调整原因</label>
                    <textarea class="form-control" id="adjustmentReason" rows="3" placeholder="请详细说明金额调整的原因..." required></textarea>
                    <div class="form-text">此记录将保存在结算备注中，用于后续对账</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmEditAmount">确认修改</button>
            </div>
        </div>
    </div>
</div>
<!-- 图片查看模态框 -->
<div class="modal fade" id="imageViewerModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <img id="enlargedImage" src="" class="img-fluid" style="max-height: 80vh;">
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

<style>
/* 日期选择器样式 */
.date-range-picker {
    background: white;
    border: 1px solid #ced4da;
    border-radius: 0.375rem;
    padding: 0.375rem 0.75rem;
}

.date-range-picker:focus {
    border-color: #86b7fe;
    outline: 0;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

/* 图片放大样式 */
.img-enlargeable {
    cursor: zoom-in;
    transition: transform 0.2s;
}

.img-enlargeable:hover {
    transform: scale(1.02);
}

/* 日期选择器下拉菜单 */
.date-range-dropdown {
    position: absolute;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    z-index: 1050;
    padding: 10px;
    display: none;
    min-width: 300px;
}

.date-range-option {
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 3px;
}

.date-range-option:hover {
    background: #f8f9fa;
}

/* 导出模态框样式 */
.export-option {
    padding: 8px 12px;
    border-radius: 4px;
    margin-bottom: 5px;
}

.export-option:hover {
    background-color: #f8f9fa;
}

.export-option input[type="radio"] {
    margin-right: 8px;
}

.export-option label {
    margin-bottom: 0;
    cursor: pointer;
}

/* 结算截图上传区域样式 - 增大上传区域 */
.settlement-screenshot-upload {
    min-height: 120px;
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background-color: #f8f9fa;
    transition: all 0.3s ease;
    cursor: pointer;
}

.settlement-screenshot-upload:hover {
    border-color: #0d6efd;
    background-color: #e7f1ff;
}

.settlement-screenshot-upload.dragover {
    border-color: #0d6efd;
    background-color: #d1e7ff;
}

.settlement-screenshot-preview {
    max-height: 200px;
    object-fit: contain;
    border-radius: 4px;
}

/* 优化筛选表单布局 */
.form-label {
    font-weight: 500;
    margin-bottom: 0.5rem;
}
</style>

<script>
// 导出相关功能
let selectedSettlements = new Set();

// 全选/取消全选
function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.settlement-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
        if (checkbox.checked) {
            selectedSettlements.add(cb.value);
        } else {
            selectedSettlements.delete(cb.value);
        }
    });
    updateSelectedCount();
}

// 更新选中数量
function updateSelectedCount() {
    selectedSettlements.clear();
    document.querySelectorAll('.settlement-checkbox:checked').forEach(cb => {
        selectedSettlements.add(cb.value);
    });
    const selectedCountElement = document.getElementById('selected_count');
    if (selectedCountElement) {
        selectedCountElement.textContent = selectedSettlements.size;
    }
    
    // 更新单选按钮状态
    const exportSelected = document.getElementById('export_selected');
    if (exportSelected) {
        if (selectedSettlements.size === 0) {
            exportSelected.disabled = true;
            if (exportSelected.checked) {
                document.getElementById('export_current').checked = true;
            }
        } else {
            exportSelected.disabled = false;
        }
    }
}

// 显示导出模态框
function showExportModal() {
    // 更新选中计数
    updateSelectedCount();
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('exportModal'));
    modal.show();
}

// 执行导出
function performExport() {
    const exportScope = document.querySelector('input[name="export_scope"]:checked').value;
    
    let url = 'settlements.php?export=settlements&export_type=' + exportScope;
    
    if (exportScope === 'selected') {
        if (selectedSettlements.size === 0) {
            showToast('请先选择要导出的结算记录', 'warning');
            return false;
        }
        url += '&selected_ids=' + Array.from(selectedSettlements).join(',');
    }
    
    // 添加筛选条件
    const status = document.getElementById('status') ? document.getElementById('status').value : '';
    const user_id = document.getElementById('user_id') ? document.getElementById('user_id').value : '';
    const phone = document.getElementById('phone') ? document.getElementById('phone').value : '';
    const date_range = document.getElementById('date_range') ? document.getElementById('date_range').value : '';
    const page = <?php echo $page; ?>;
    
    if (status) url += '&status=' + encodeURIComponent(status);
    if (user_id) url += '&user_id=' + encodeURIComponent(user_id);
    if (phone) url += '&phone=' + encodeURIComponent(phone);
    if (date_range) url += '&date_range=' + encodeURIComponent(date_range);
    url += '&page=' + page;
    
    console.log('导出URL:', url); // 调试用
    
    // 显示导出提示
    showToast('正在生成导出文件，请稍候...', 'info');
    
    // 开始下载 - 使用新窗口打开确保不会丢失当前页面状态
    const downloadWindow = window.open(url, '_blank');
    
    // 检查下载是否完成（这是一个简单的方法，实际中可能需要更复杂的检测）
    setTimeout(() => {
        if (downloadWindow && !downloadWindow.closed) {
            downloadWindow.close();
        }
    }, 5000);
    
    return true;
}

// 初始化导出功能
function initExportFunction() {
    // 更新选中计数
    updateSelectedCount();
    
    // 绑定导出确认按钮
    const confirmExportBtn = document.getElementById('confirmExport');
    if (confirmExportBtn) {
        confirmExportBtn.addEventListener('click', function() {
            if (performExport()) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('exportModal'));
                modal.hide();
            }
        });
    }
    
    // 为每个复选框添加事件监听
    document.querySelectorAll('.settlement-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedCount);
    });
}

// 改进的日期范围选择器实现
function initDateRangePicker() {
    const dateRangeInput = document.getElementById('date_range');
    
    // 检查是否已存在下拉菜单，如果存在则移除
    const existingDropdown = dateRangeInput.parentNode.querySelector('.date-range-dropdown');
    if (existingDropdown) {
        existingDropdown.remove();
    }
    
    const dropdown = document.createElement('div');
    dropdown.className = 'date-range-dropdown mt-1';
    dropdown.innerHTML = `
        <div class="date-range-option" data-range="today">今天</div>
        <div class="date-range-option" data-range="yesterday">昨天</div>
        <div class="date-range-option" data-range="last7">最近7天</div>
        <div class="date-range-option" data-range="last30">最近30天</div>
        <div class="date-range-option" data-range="thisMonth">本月</div>
        <div class="date-range-option" data-range="lastMonth">上个月</div>
        <hr class="my-2">
        <div class="custom-date-range">
            <div class="mb-2"><strong>自定义日期范围：</strong></div>
            <div class="row g-2">
                <div class="col">
                    <label class="form-label small">开始日期</label>
                    <input type="date" class="form-control form-control-sm" id="customStartDate">
                </div>
                <div class="col-auto align-self-center">至</div>
                <div class="col">
                    <label class="form-label small">结束日期</label>
                    <input type="date" class="form-control form-control-sm" id="customEndDate">
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-12">
                    <button type="button" class="btn btn-primary btn-sm w-100" onclick="applyCustomDateRange()">应用自定义范围</button>
                </div>
            </div>
        </div>
    `;
    
    dateRangeInput.parentNode.appendChild(dropdown);
    
    // 显示/隐藏下拉菜单 - 改进的点击处理
    dateRangeInput.addEventListener('click', function(e) {
        e.stopPropagation();
        const allDropdowns = document.querySelectorAll('.date-range-dropdown');
        allDropdowns.forEach(d => {
            if (d !== dropdown) d.style.display = 'none';
        });
        dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
    });
    
    // 点击选项 - 防止事件冒泡
    dropdown.querySelectorAll('.date-range-option[data-range]').forEach(option => {
        option.addEventListener('click', function(e) {
            e.stopPropagation();
            const range = this.getAttribute('data-range');
            applyDateRange(range);
            dropdown.style.display = 'none';
        });
    });
    
    // 点击下拉菜单内部时不关闭
    dropdown.addEventListener('click', function(e) {
        e.stopPropagation();
    });
    
    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', function() {
        dropdown.style.display = 'none';
    });
}

// 应用预设日期范围
function applyDateRange(range) {
    const today = new Date();
    let startDate, endDate;
    
    switch(range) {
        case 'today':
            startDate = today;
            endDate = today;
            break;
        case 'yesterday':
            startDate = new Date(today);
            startDate.setDate(today.getDate() - 1);
            endDate = startDate;
            break;
        case 'last7':
            startDate = new Date(today);
            startDate.setDate(today.getDate() - 6);
            endDate = today;
            break;
        case 'last30':
            startDate = new Date(today);
            startDate.setDate(today.getDate() - 29);
            endDate = today;
            break;
        case 'thisMonth':
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            break;
        case 'lastMonth':
            startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            endDate = new Date(today.getFullYear(), today.getMonth(), 0);
            break;
    }
    
    const dateRangeInput = document.getElementById('date_range');
    dateRangeInput.value = formatDate(startDate) + ' - ' + formatDate(endDate);
}

// 应用自定义日期范围
function applyCustomDateRange() {
    const startDate = document.getElementById('customStartDate').value;
    const endDate = document.getElementById('customEndDate').value;
    
    if (startDate && endDate) {
        const dateRangeInput = document.getElementById('date_range');
        dateRangeInput.value = startDate + ' - ' + endDate;
        document.querySelector('.date-range-dropdown').style.display = 'none';
    } else {
        showToast('请选择开始日期和结束日期', 'warning');
    }
}

// 清除日期范围
function clearDateRange() {
    document.getElementById('date_range').value = '';
}

// 格式化日期为 YYYY-MM-DD
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 图片放大功能
function initImageEnlarge() {
    // 为所有图片添加点击放大功能
    document.addEventListener('click', function(e) {
        if (e.target.tagName === 'IMG' && 
            (e.target.classList.contains('img-enlargeable') || 
             e.target.parentNode.tagName === 'A' || 
             e.target.closest('.card img'))) {
            
            const imgSrc = e.target.src;
            enlargeImage(imgSrc);
        }
    });
    
    // 动态添加可放大类到图片
    setTimeout(() => {
        const images = document.querySelectorAll('img');
        images.forEach(img => {
            // 为收款码、截图等图片添加可放大类
            if (img.src && (img.src.includes('uploads/') || 
                img.closest('.card') || 
                img.alt?.includes('收款码') || 
                img.parentNode.tagName === 'A')) {
                img.classList.add('img-enlargeable');
            }
        });
    }, 1000);
}

// 初始化结算截图上传区域
function initSettlementScreenshotUpload() {
    const screenshotUpload = document.getElementById('settlementScreenshots');
    if (!screenshotUpload) return;
    
    // 创建自定义上传区域
    const customUploadArea = document.createElement('div');
    customUploadArea.className = 'settlement-screenshot-upload mb-3';
    customUploadArea.innerHTML = `
        <div class="upload-content">
            <i class="bi bi-cloud-arrow-up display-4 text-muted"></i>
            <p class="mt-2 mb-1">点击或拖拽图片到此处上传</p>
            <p class="small text-muted">支持 JPG、PNG、GIF 格式，最大 5MB/张</p>
            <p class="small text-muted">可多选文件，建议上传结算凭证截图</p>
        </div>
    `;
    
    screenshotUpload.parentNode.insertBefore(customUploadArea, screenshotUpload);
    screenshotUpload.style.display = 'none';
    
    // 点击自定义区域触发文件选择
    customUploadArea.addEventListener('click', function() {
        screenshotUpload.click();
    });
    
    // 拖拽功能
    customUploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('dragover');
    });
    
    customUploadArea.addEventListener('dragleave', function() {
        this.classList.remove('dragover');
    });
    
    customUploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');
        
        if (e.dataTransfer.files.length > 0) {
            screenshotUpload.files = e.dataTransfer.files;
            updateScreenshotPreview();
        }
    });
    
    // 文件选择变化时更新预览
    screenshotUpload.addEventListener('change', updateScreenshotPreview);
    
    function updateScreenshotPreview() {
        const files = screenshotUpload.files;
        if (files.length === 0) {
            customUploadArea.innerHTML = `
                <div class="upload-content">
                    <i class="bi bi-cloud-arrow-up display-4 text-muted"></i>
                    <p class="mt-2 mb-1">点击或拖拽图片到此处上传</p>
                    <p class="small text-muted">支持 JPG、PNG、GIF 格式，最大 5MB/张</p>
                    <p class="small text-muted">可多选文件，建议上传结算凭证截图</p>
                </div>
            `;
            return;
        }
        
        let previewHTML = `<div class="row">`;
        
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();
            
            reader.onload = function(e) {
                const imgElement = document.getElementById(`preview-${i}`);
                if (imgElement) {
                    imgElement.src = e.target.result;
                }
            };
            
            reader.readAsDataURL(file);
            
            previewHTML += `
                <div class="col-md-3 mb-2">
                    <div class="card">
                        <img id="preview-${i}" src="" class="card-img-top settlement-screenshot-preview" alt="预览">
                        <div class="card-body p-2">
                            <small class="text-muted">${file.name}</small>
                        </div>
                    </div>
                </div>
            `;
        }
        
        previewHTML += `</div>`;
        customUploadArea.innerHTML = previewHTML;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initDateRangePicker();
    initImageEnlarge();
    initExportFunction();
    initSettlementScreenshotUpload();
    
    // 为导出按钮添加点击事件
    const exportBtn = document.querySelector('button[data-bs-target="#exportModal"]');
    if (exportBtn) {
        exportBtn.addEventListener('click', showExportModal);
    }
    
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 修复：全局处理模态框关闭事件
    document.addEventListener('hidden.bs.modal', function(event) {
        // 检查是否还有打开的模态框
        const openModals = document.querySelectorAll('.modal.show');
        if (openModals.length === 0) {
            // 没有打开的模态框，清理背景
            const backdrops = document.querySelectorAll('.modal-backdrop');
            backdrops.forEach(backdrop => {
                backdrop.remove();
            });
            document.body.classList.remove('modal-open');
            document.body.style = '';
        }
    });
});

// 其他现有函数保持不变...
function showSettlementDetails(settlementId) {
    // 显示加载状态
    document.getElementById('settlementDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('settlementDetailsModal'));
    modal.show();
    
    // 加载结算详情
    fetch('api/settlement_details.php?id=' + settlementId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const settlement = data.data;
                const statusClass = {
                    'pending': 'warning',
                    'completed': 'success'
                };
                const statusText = {
                    'pending': '待结算',
                    'completed': '已结算'
                };
                const typeText = {
                    'commission': '结本金',
                    'principal_commission': '结本金+佣金'
                };
                
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>结算ID：</strong></td><td>${settlement.id}</td></tr>
                                <tr><td><strong>用户：</strong></td><td>${settlement.username} (${settlement.phone})</td></tr>
                                <tr><td><strong>群组：</strong></td><td>${settlement.group_name_label}</td></tr>
                                <tr><td><strong>总金额：</strong></td><td class="text-primary fw-bold">¥${parseFloat(settlement.total_amount).toFixed(2)}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>状态：</strong></td><td>
                                    <span class="badge bg-${statusClass[settlement.status]}">${statusText[settlement.status]}</span>
                                </td></tr>
                                <tr><td><strong>创建时间：</strong></td><td>${new Date(settlement.created_at).toLocaleString('zh-CN')}</td></tr>
                `;
                
                if (settlement.settled_at) {
                    html += `<tr><td><strong>结算时间：</strong></td><td>${new Date(settlement.settled_at).toLocaleString('zh-CN')}</td></tr>`;
                }
                
                html += `
                            </table>
                        </div>
                    </div>
                `;
                
                // 显示结算备注和截图 - 修改图片为可点击放大
                if (settlement.settlement_info || (settlement.settlement_screenshots && settlement.settlement_screenshots.length > 0)) {
                    html += `
                        <div class="mt-4">
                            <h6>结算信息</h6>
                    `;
                    
                    if (settlement.settlement_info) {
                        html += `<div class="mb-3"><strong>结算备注：</strong><p class="mb-0">${settlement.settlement_info.replace(/\n/g, '<br>')}</p></div>`;
                    }
                    
                    if (settlement.settlement_screenshots && settlement.settlement_screenshots.length > 0) {
                        html += `<div class="mb-3"><strong>结算截图：</strong><div class="row mt-2">`;
                        settlement.settlement_screenshots.forEach(screenshot => {
                            html += `
                                <div class="col-md-3 mb-3">
                                    <div class="card">
                                        <a href="javascript:void(0)" onclick="enlargeImage('${screenshot.url}')">
                                            <img src="${screenshot.url}" class="card-img-top img-enlargeable" style="height: 120px; object-fit: cover;">
                                        </a>
                                        <div class="card-body p-2">
                                            <button type="button" class="btn btn-sm btn-outline-danger w-100" onclick="deleteSettlementScreenshot(${settlement.id}, '${screenshot.filename}')">
                                                <i class="bi bi-trash"></i> 删除
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        html += `</div></div>`;
                    }
                    
                    html += `</div>`;
                }
                
                // 显示关联的订单（去重显示）
                html += `
                    <div class="mt-4">
                        <h6>关联的订单 (${settlement.order_count}个)</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>订单ID</th>
                                        <th>商品名称</th>
                                        <th>收货地</th>
                                        <th>下单平台</th>
                                        <th>物流单号</th>
                                        <th>下单金额</th>
                                    </tr>
                                </thead>
                                <tbody>
                `;
                
                settlement.orders.forEach(order => {
                    html += `
                        <tr>
                            <td>${order.id}</td>
                            <td>${order.product_name}</td>
                            <td>${order.delivery_location_label}</td>
                            <td>${order.order_platform_label}</td>
                            <td>${order.tracking_no}</td>
                            <td>¥${parseFloat(order.order_amount).toFixed(2)}</td>
                        </tr>
                    `;
                });
                
                html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                `;
                
                // 显示结算单子详情（每次结算的详细记录） - 修改图片为可点击放大
                html += `
                    <div class="mt-4">
                        <h6>结算单子详情 (${settlement.detail_count}条记录)</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>结算时间</th>
                                        <th>订单ID</th>
                                        <th>商品名称</th>
                                        <th>结算类型</th>
                                        <th>结算金额</th>
                                        <th>结算信息</th>
                                        <th>操作员</th>
                                        <th>截图</th>
                                    </tr>
                                </thead>
                                <tbody>
                `;
                
                settlement.settlement_details.forEach(detail => {
                    const detailTypeText = {
                        'commission': '结本金',
                        'principal_commission': '结本金+佣金'
                    };
                    
                    html += `
                        <tr>
                            <td>${new Date(detail.created_at).toLocaleString('zh-CN')}</td>
                            <td>${detail.order_id}</td>
                            <td>${detail.product_name}</td>
                            <td>
                                <span class="badge bg-${detail.settlement_type === 'commission' ? 'info' : 'primary'}">
                                    ${detailTypeText[detail.settlement_type]}
                                </span>
                            </td>
                            <td class="text-success fw-bold">¥${parseFloat(detail.settlement_amount).toFixed(2)}</td>
                            <td>${detail.settlement_info || '-'}</td>
                            <td>${detail.admin_name}</td>
                            <td>
                    `;
                    
                    if (detail.screenshot_urls && detail.screenshot_urls.length > 0) {
                        detail.screenshot_urls.forEach(screenshot => {
                            html += `
                                <div class="mb-1">
                                    <a href="javascript:void(0)" onclick="enlargeImage('${screenshot.url}')" class="btn btn-sm btn-outline-info me-1">
                                        <i class="bi bi-image"></i> 查看
                                    </a>
                                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteSettlementDetailScreenshot(${detail.id}, '${screenshot.filename}')">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            `;
                        });
                    } else {
                        html += '-';
                    }
                    
                    html += `</td></tr>`;
                });
                
                html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                `;
                
                document.getElementById('settlementDetailsContent').innerHTML = html;
                
                // 重新初始化图片放大功能
                setTimeout(initImageEnlarge, 100);
            } else {
                document.getElementById('settlementDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('settlementDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 图片放大函数
function enlargeImage(src) {
    const enlargedImage = document.getElementById('enlargedImage');
    const imageModal = new bootstrap.Modal(document.getElementById('imageViewerModal'));
    
    // 设置图片源
    enlargedImage.src = src;
    
    // 显示模态框
    imageModal.show();
    
    // 修复：确保模态框关闭时正确清理
    const imageViewerModal = document.getElementById('imageViewerModal');
    imageViewerModal.addEventListener('hidden.bs.modal', function() {
        // 移除所有可能残留的模态框背景
        const backdrops = document.querySelectorAll('.modal-backdrop');
        backdrops.forEach(backdrop => {
            backdrop.remove();
        });
        
        // 确保body样式正确恢复
        document.body.classList.remove('modal-open');
        document.body.style = '';
        
        // 重置图片源，避免缓存问题
        enlargedImage.src = '';
    });
}

// 其他函数保持不变...
function deleteSettlementScreenshot(settlementId, filename) {
    if (!confirm('确定要删除这张结算截图吗？')) {
        return;
    }
    
    fetch('api/delete_settlement_screenshot.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            settlement_id: settlementId,
            filename: filename
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('截图删除成功', 'success');
            // 重新加载详情
            showSettlementDetails(settlementId);
        } else {
            showToast('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showToast('删除失败: ' + error.message, 'danger');
    });
}

function deleteSettlementDetailScreenshot(detailId, filename) {
    if (!confirm('确定要删除这张结算截图吗？')) {
        return;
    }
    
    fetch('api/delete_settlement_detail_screenshot.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            detail_id: detailId,
            filename: filename
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('截图删除成功', 'success');
            location.reload();
        } else {
            showToast('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showToast('删除失败: ' + error.message, 'danger');
    });
}

function showEditSettlementAmount(settlementId) {
    // 创建模态框HTML
    const modalHtml = `
        <div class="modal fade" id="editSettlementAmountModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">修改结算金额</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="newAmount" class="form-label">新的结算金额</label>
                            <input type="number" class="form-control" id="newAmount" step="0.01" min="0.01" required>
                            <div class="form-text">请输入正确的金额，支持小数点后两位</div>
                        </div>
                        <div class="mb-3">
                            <label for="adjustmentReason" class="form-label">调整原因</label>
                            <textarea class="form-control" id="adjustmentReason" rows="3" placeholder="请详细说明金额调整的原因..." required></textarea>
                            <div class="form-text">此记录将保存在结算备注中，用于后续对账</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="updateSettlementAmount(${settlementId})">确认修改</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('editSettlementAmountModal'));
    modal.show();
    
    // 加载当前金额
    fetch('api/settlement_details.php?id=' + settlementId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('newAmount').value = parseFloat(data.data.total_amount).toFixed(2);
            }
        });
    
    // 清理
    document.getElementById('editSettlementAmountModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

function showCompleteSettlement(settlementId) {
    // 显示加载状态
    document.getElementById('completeSettlementContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('completeSettlementModal'));
    modal.show();
    
    // 设置确认按钮点击事件
    document.getElementById('confirmCompleteSettlement').onclick = function() {
        completeSettlement(settlementId);
    };
    
    // 加载结算详情
    fetch('api/settlement_complete_details.php?id=' + settlementId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const settlement = data.data;
                const typeText = {
                    'commission': '本金',
                    'principal_commission': '本金+佣金'
                };
                
                let html = `
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i>
                        <strong>结算说明：</strong>确认结算后将向用户发送推送通知，此操作不可撤销。
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6>结算信息</h6>
                            <table class="table table-sm">
                                <tr><td><strong>结算ID：</strong></td><td>${settlement.id}</td></tr>
                                <tr><td><strong>用户：</strong></td><td>${settlement.username} (${settlement.phone})</td></tr>
                                <tr><td><strong>群组：</strong></td><td>${settlement.group_name_label}</td></tr>
                                <tr><td><strong>结算类型：</strong></td><td>${typeText[settlement.settlement_type]}</td></tr>
                                <tr><td><strong>总金额：</strong></td><td class="text-primary fw-bold">¥${parseFloat(settlement.total_amount).toFixed(2)}</td></tr>
                                <tr><td><strong>创建时间：</strong></td><td>${new Date(settlement.created_at).toLocaleString('zh-CN')}</td></tr>
                            </table>
                            <!-- 结算信息输入 -->
                            <div class="mb-3">
                                <label for="settlementInfo" class="form-label">结算备注信息</label>
                                <textarea class="form-control" id="settlementInfo" name="settlement_info" rows="3" placeholder="请输入结算说明、备注等"></textarea>
                            </div>
                            
                            <!-- 改进的结算截图上传区域 -->
                            <div class="mb-3">
                                <label class="form-label">结算截图上传</label>
                                <div id="screenshotUploadArea">
                                    <input type="file" class="form-control" id="settlementScreenshots" name="settlement_screenshots[]" accept="image/*" multiple>
                                </div>
                                <div class="form-text">支持多张图片，格式：JPG、PNG、GIF，最大 5MB/张</div>
                            </div>
                    
                        </div>
                        <div class="col-md-6">
                            <h6>用户收款信息</h6>
                `;
                
                if (settlement.wechat_account || settlement.wechat_nickname) {
                    html += `
                        <div class="mb-3">
                            <strong>微信信息：</strong><br>
                            ${settlement.wechat_account ? '账号: ' + settlement.wechat_account + '<br>' : ''}
                            ${settlement.wechat_nickname ? '昵称: ' + settlement.wechat_nickname : ''}
                        </div>
                    `;
                }
                
                if (settlement.alipay_account) {
                    html += `
                        <div class="mb-3">
                            <strong>支付宝账号：</strong><br>
                            ${settlement.alipay_account}
                        </div>
                    `;
                }
                if (settlement.bank_card_number) {
                    html += `
                        <div class="mb-3">
                            <strong>银行卡信息：</strong><br>
                            ${settlement.account_holder ? '姓名: ' + settlement.account_holder + '<br>' : ''}
                            ${settlement.bank_name ? '银行: ' + settlement.bank_name + '<br>' : ''}
                             ${settlement.bank_card_number ? '银行卡号: ' + settlement.bank_card_number : ''}
                        </div>
                    `;
                }
                
                // 修改收款码图片为可点击放大
                if (settlement.wechat_qr_url) {
                    html += `
                        <div class="mb-3">
                            <strong>微信收款码：</strong><br>
                            <a href="javascript:void(0)" onclick="enlargeImage('${settlement.wechat_qr_url}')">
                                <img src="${settlement.wechat_qr_url}" class="img-fluid rounded border mt-1 img-enlargeable" style="max-height: 150px;">
                            </a>
                        </div>
                    `;
                }
                
                if (settlement.alipay_qr_url) {
                    html += `
                        <div class="mb-3">
                            <strong>支付宝收款码：</strong><br>
                            <a href="javascript:void(0)" onclick="enlargeImage('${settlement.alipay_qr_url}')">
                                <img src="${settlement.alipay_qr_url}" class="img-fluid rounded border mt-1 img-enlargeable" style="max-height: 150px;">
                            </a>
                        </div>
                    `;
                }
                
                if (!settlement.wechat_account && !settlement.alipay_account && !settlement.wechat_qr_url && !settlement.alipay_qr_url) {
                    html += `
                        <div class="text-muted">
                            <i class="bi bi-exclamation-triangle"></i> 该用户暂未设置收款信息
                        </div>
                    `;
                }
                
                html += `
                        </div>
                    </div>
                `;
                
                // 显示关联的订单
                html += `
                    <div class="mt-4">
                        <h6>关联的订单 (${settlement.order_count}个)</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>订单ID</th>
                                        <th>商品名称</th>
                                        <th>收货地</th>
                                        <th>下单平台</th>
                                        <th>物流单号</th>
                                        <th>下单金额</th>
                                        <th>结算金额</th>
                                    </tr>
                                </thead>
                                <tbody>
                `;
                
                settlement.orders.forEach(order => {
                    html += `
                        <tr>
                            <td>${order.id}</td>
                            <td>${order.product_name}</td>
                            <td>${order.delivery_location_label}</td>
                            <td>${order.order_platform_label}</td>
                            <td>${order.tracking_no}</td>
                            <td>¥${parseFloat(order.order_amount).toFixed(2)}</td>
                            <td class="text-success">¥${parseFloat(order.settlement_amount || order.order_amount).toFixed(2)}</td>
                        </tr>
                    `;
                });
                
                html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                `;
                
                document.getElementById('completeSettlementContent').innerHTML = html;
                
                // 重新初始化截图上传功能
                setTimeout(initSettlementScreenshotUpload, 100);
                // 重新初始化图片放大功能
                setTimeout(initImageEnlarge, 100);
            } else {
                document.getElementById('completeSettlementContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('completeSettlementContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

function completeSettlement(settlementId) {
    const settlementInfo = document.getElementById('settlementInfo') ? document.getElementById('settlementInfo').value : '';
    const screenshotFiles = document.getElementById('settlementScreenshots') ? document.getElementById('settlementScreenshots').files : [];
    
    if (!confirm('确定要完成这个结算吗？此操作将向用户发送推送通知，且不可撤销。')) {
        return;
    }
    
    const modal = document.getElementById('completeSettlementModal');
    if (modal.dataset.submitting === 'true') {
        showToast('正在处理中，请稍候...', 'warning');
        return;
    }
    
    modal.dataset.submitting = 'true';
    
    const confirmBtn = document.getElementById('confirmCompleteSettlement');
    const originalText = confirmBtn.innerHTML;
    confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
    confirmBtn.disabled = true;
    
    const formData = new FormData();
    formData.append('action', 'complete');
    formData.append('settlement_id', settlementId);
    formData.append('settlement_info', settlementInfo);
    
    if (screenshotFiles.length > 0) {
        for (let i = 0; i < screenshotFiles.length; i++) {
            formData.append('settlement_screenshots[]', screenshotFiles[i]);
        }
    }
    
    fetch('settlements.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(html => {
        location.reload();
    })
    .catch(error => {
        showToast('操作失败：' + error.message, 'danger');
        confirmBtn.innerHTML = originalText;
        confirmBtn.disabled = false;
        modal.dataset.submitting = 'false';
    });
}

// 显示修改结算信息模态框
function showEditSettlementModal(settlementId) {
    // 显示加载状态
    document.getElementById('editSettlementContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('editSettlementModal'));
    modal.show();
    
    // 加载编辑表单
    fetch('api/edit_settlement_form.php?id=' + settlementId)
        .then(response => response.text())
        .then(html => {
            document.getElementById('editSettlementContent').innerHTML = html;
        })
        .catch(error => {
            document.getElementById('editSettlementContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 显示修改结算金额模态框
function showEditSettlementAmount(settlementId) {
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('editSettlementAmountModal'));
    modal.show();
    
    // 设置确认按钮点击事件
    document.getElementById('confirmEditAmount').onclick = function() {
        updateSettlementAmount(settlementId);
    };
    
    // 加载当前金额
    fetch('api/settlement_details.php?id=' + settlementId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('newAmount').value = parseFloat(data.data.total_amount).toFixed(2);
            }
        });
}

// 更新结算金额
function updateSettlementAmount(settlementId) {
    const newAmount = document.getElementById('newAmount').value;
    const adjustmentReason = document.getElementById('adjustmentReason').value;
    
    if (!newAmount || parseFloat(newAmount) <= 0) {
        showToast('请输入有效的金额', 'danger');
        return;
    }
    
    if (!adjustmentReason.trim()) {
        showToast('请填写金额调整原因', 'danger');
        return;
    }
    
    if (!confirm('确定要修改结算金额吗？此操作将记录在结算备注中，且不可撤销。')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('settlement_id', settlementId);
    formData.append('new_amount', newAmount);
    formData.append('adjustment_reason', adjustmentReason);
    
    fetch('api/update_settlement_amount.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('结算金额更新成功', 'success');
            // 关闭模态框并刷新页面
            const modal = bootstrap.Modal.getInstance(document.getElementById('editSettlementAmountModal'));
            modal.hide();
            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            showToast('更新失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showToast('更新失败: ' + error.message, 'danger');
    });
}
</script>